package com.unionFind.byMySelf;

import com.UF;

import java.util.Arrays;

public class QuickFind implements UF {

//    Integer[] boxedId;

    private int count;

    private int[] id;

//    private BinarySearchByMySelf<Integer> binarySearchByMySelf;

    public QuickFind(int count) {
        this.count = count;
        int[] id = new int[count];
        for (int i = 0; i < id.length; i++) {
            id[i] = i;
        }
        this.id = id;
//        this.boxedId = Arrays.stream(id).boxed().toArray(Integer[]::new);
//        this.binarySearchByMySelf = new BinarySearchByMySelf<Integer>(boxedId, true);
    }

    public void union(int p, int q) {
        int portionP = this.find(p);
        int portionQ = this.find(q);

        if (portionQ == portionP) {
            return;
        }
//        boolean canUsePortionP = portionP != -1;

//        将要被删除（替换、合并）的分量
//        int portionForReplace = canUsePortionP ? portionQ : portionP;
//        合并后的分量
//        int combinePortion = canUsePortionP ? portionP : portionQ;
//        List<Integer> belongToPointPIndex = new ArrayList(boxedId.length);

        for (int i = 0; i < this.id.length; i++) {
            if (this.id[i] == portionP) {
                this.id[i] = portionQ;
                System.out.printf("已经将触点【%d】的分量【%d】改为了触点【%d】\n", i, portionP, portionQ);
            }
        }
        this.count--;
        this.count();
    }

    public int find(int p) {
       return this.id[p];
//        return BinarySearchByMySelf.findIndex(this.id, p);// 不能使用二分查找，因为分量一变之后，数组中的元素就不是有序的了
    }

    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }

    public int count() {
        System.out.println(Arrays.toString(this.id));
        return this.count;
    }
}
